package com.android.powerbankpad.download;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import com.lzy.okgo.https.HttpsUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.cache.FilePathUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FileDownloader {
    private static final int BUFFER_SIZE = 8192; // 8 KB
    private OkHttpClient client;
    private Handler handler;

    private static FileDownloader sPubUiUtils;



    public static FileDownloader getInstance() {
        if (sPubUiUtils == null) {
            sPubUiUtils = new FileDownloader();
        }
        return sPubUiUtils;
    }

    private FileDownloader() {
        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();

        client = new OkHttpClient.Builder()
                .sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager)
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        handler = new Handler(Looper.getMainLooper());
    }


    public Observable<Object> downloadFile(String url, String downloadPath,float fileSize, ProgressListener listener) {
        LogcatUtils.e("Download img 执行下载 Img   " + url + " downloadPath " + downloadPath);
        return Observable.fromCallable(() -> {
            File outputFile = new File(downloadPath);
            long downloadedBytes = 0;

            if (outputFile.exists()) {
                downloadedBytes = outputFile.length();
            }

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Range", "bytes=" + downloadedBytes + "-")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.code() != 206 && response.code() != 200) {
                    LogcatUtils.e("Download img 执行下载 Img 不支持断点  ");

                }

                try (InputStream inputStream = response.body().byteStream();
                     RandomAccessFile randomAccessFile = new RandomAccessFile(outputFile, "rw")) {

                    randomAccessFile.seek(downloadedBytes);
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int bytesRead;
                    long totalBytesRead = downloadedBytes;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        randomAccessFile.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        // 计算下载进度并通知主线程更新
                        //LogcatUtils.e("Download img totalBytesRead "+totalBytesRead +" fileSize "+fileSize);

                        float progress =  (totalBytesRead * 100 / fileSize);
                        notifyProgress(listener, progress);
                    }
                } finally {
                    // 关闭输入流和输出流
                    response.body().close();
                }

            }
            return new Object();
        }).subscribeOn(Schedulers.io());
    }

    private void notifyProgress(ProgressListener listener, float progress) {
        if (listener != null) {
            handler.postDelayed(() -> listener.onProgress(progress), 1000);
        }
    }

    public interface ProgressListener {
        void onProgress(float progress);
    }
}
